require "config-biz"
isActivity = false
checkActivityTime = 0

    
function tcp_receive(sck, c)
    print("receive:"..c) 
    -- need to check wifi's password length >= 8
    local configs = cjson.decode(c)
    local result = __check_cloud_configs(configs)
    if(configs.action == "initConfig") then 
        if(result.isOk == false) then 
            local reportMsg = {}
            reportMsg.errors = result.msg
            --reportMsg.aps = __getApsArrayByTmp()
            reportMsg.action = "report_error"
            local msg = cjson.encode(reportMsg).."\n\r"
            print("tcp to send:"..msg)
            sck:send(msg)
        else
            updateConfigByText(cjson.encode(configs.configs))
            excludeWifi = {}
            reTryConnectToCloud = true
            wifi.sta.disconnect()
        end
    end
end
function tcp_disconnection(sck, c)
    print("disconnection")
    activity()
    wifi.sta.disconnect()
end
function tcp_connection(sck, c)
    print("connection")
    activity()
    local reportMsg = {}
    reportMsg.errors = errors
    reportMsg.from = self
    reportMsg.action = "init_configs"
    msg = cjson.encode(reportMsg).."\n\r"
    print("tcp to send:"..msg)
    sck:send(msg)
    excludeWifi={}
    errors = ""
end


function __check_cloud_configs(configs) 
    local result = {}
    result["isOk"]=true
    result["msg"] = ""
    
    if(configs ~= nil) then
        if(configs.action == "initConfig") then 
            local wifisConfigs = configs["configs"]["wifis"]
            --password.len() need >= 8
            if(wifisConfigs ~= nil) then
                for i,v in pairs(wifisConfigs) do
                    if(string.len(v["password"]) < 8) then 
                        result.isOk = false
                        result.msg = "password.len() need >= 8"
                        return result
                    end
                end
            end
        end
    end
    return result
end

function __init_wifi_success(t)
    deactivity()
    print("__init_wifi_success:")
    srv = net.createConnection(net.TCP, 0)
    srv:on("receive", tcp_receive)
    srv:on("connection", tcp_connection)
    srv:on("disconnection", tcp_disconnection)
    local configs = getInitConfig()
    local tcpConfig = configs["tcp"]
    print("to connect tcp:"..tcpConfig["addr"]..":"..tcpConfig["port"])
    srv:connect(tcpConfig["port"],tcpConfig["addr"])
end


function deactivity()
    isActivity = false
end
function activity() 
    isActivity = true
    checkActivityTime = 0
end
function checkActivity() 
    if(isActivity == false and checkActivityTime >= 5) then
        wifi.sta.getap(1, connectToWifi)
    elseif(isActivity == false) then
        checkActivityTime = checkActivityTime + 1
    end
end

